﻿using Dapper;
using log4net;
using MySql.Data.MySqlClient;
using StoreProject.BLL.StackBLL;
using StoreProject.DBUtil;
using StoreProject.Entity.StackEntity;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySqlHelper = StoreProject.DBUtil.MySqlHelper;

namespace StoreProject.Forms.StackForms.Operate
{
    public partial class StackOutSettingForm : Form
    {
        ILog _log = LogManager.GetLogger("StackOutSettingForm");
        private StackInEntity stackInEntity;
        StackLocationBLL stackLocationBLL = new StackLocationBLL();
        StackInBLL stackInBLL = new StackInBLL();
        StackLogBLL stackLogBLL = new StackLogBLL();
        public StackOutSettingForm()
        {
            InitializeComponent();
        }
        public StackOutSettingForm(StackInEntity stackInEntity)
        {
            this.stackInEntity = stackInEntity;
            InitializeComponent();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                using (var Conn = MySqlHelper.getConnectionEx())
                {
                    MySqlTransaction trans = null;
                    try
                    {
                        Conn.Open();
                        trans = Conn.BeginTransaction();
                        stackInEntity.Type = this.cmbType.Text;
                        var newCount = Convert.ToInt32(numProductCount.Value);  //出库的数量
                        //全部出库的要修改状态，部分出库的要重新计算
                        string sql = string.Format("select * from StackIn where id = '{0}' for update;", stackInEntity.Id);
                        var readStackInEntity = Conn.QueryFirstOrDefault<StackInEntity>(sql, trans, null, null);
                        if (readStackInEntity != null && readStackInEntity.IsStack == true)
                        {
                            if (readStackInEntity.ProductCount == stackInEntity.ProductCount)
                            {
                                if (newCount == stackInEntity.ProductCount)
                                {
                                    string sql1 = string.Format("UPDATE StackIn set Type = '{1}',ProductCount = '{2}',IsStack = false where Id = '{0}'", stackInEntity.Id, stackInEntity.Type, 0);
                                    int flag = Conn.Execute(sql1, trans, null, null);
                                    if (flag == 1)
                                    {
                                        StackLogEntity stackLogEntity = new StackLogEntity();
                                        stackLogEntity.Id = Guid.NewGuid().ToString();
                                        stackLogEntity.StackOrderId = stackInEntity.Id;
                                        stackLogEntity.StackLocation = stackInEntity.StackLocation;
                                        stackLogEntity.LogType = "1";
                                        stackLogEntity.Note = "全部出库；货品：" + stackInEntity.ProductName + "从" + stackInEntity.StackLocation + "全部出库。出库类型为：" + stackInEntity.Type;
                                        stackLogEntity.CreateTime = DateTime.Now;
                                        stackLogEntity.UpdateTime = DateTime.Now;
                                        stackLogBLL.Insert(stackLogEntity);
                                    }
                                }
                                else
                                {
                                    stackInEntity.ProductCount = stackInEntity.ProductCount - newCount;

                                    string sql1 = string.Format("UPDATE StackIn set Type = '{1}',ProductCount = '{2}' where Id = '{0}'", stackInEntity.Id, stackInEntity.Type, stackInEntity.ProductCount);
                                    int flag = Conn.Execute(sql1, trans, null, null);
                                    if (flag == 1)
                                    {
                                        StackLogEntity stackLogEntity = new StackLogEntity();
                                        stackLogEntity.Id = Guid.NewGuid().ToString();
                                        stackLogEntity.StackOrderId = stackInEntity.Id;
                                        stackLogEntity.StackLocation = stackInEntity.StackLocation;
                                        stackLogEntity.LogType = "1";
                                        stackLogEntity.Note = "部分出库；货品：" + stackInEntity.ProductName + "从" + stackInEntity.StackLocation + "部分出库。出库类型为：" + stackInEntity.Type + " ；数量为：" + newCount;
                                        stackLogEntity.CreateTime = DateTime.Now;
                                        stackLogEntity.UpdateTime = DateTime.Now;
                                        stackLogBLL.Insert(stackLogEntity);
                                    }
                                }
                                trans.Commit();
                                MessageBox.Show("出库成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            else
                            {
                                trans.Commit();
                                MessageBox.Show("出库失败，库存已被修改。请重新查询并出库！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                //return;
                            }
                        }
                        else
                        {
                            trans.Commit();
                        }
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback(); //回滚
                    }
                    finally
                    {
                        trans.Dispose(); //释放
                        Conn.Close();
                        this.Close();
                    }
                }
                #region 无事务的处理方式
                //stackInEntity.Type = this.cmbType.Text;
                //var newCount = Convert.ToInt32(numProductCount.Value);  //出库的数量
                ////全部出库的要修改状态，部分出库的要重新计算
                //if (newCount == stackInEntity.ProductCount)
                //{
                //    stackInEntity.ProductCount = 0;
                //    stackInEntity.IsStack = false;
                //    var flag = stackInBLL.Update(stackInEntity);
                //    if (flag)
                //    {
                //        StackLogEntity stackLogEntity = new StackLogEntity();
                //        stackLogEntity.Id = Guid.NewGuid().ToString();
                //        stackLogEntity.StackOrderId = stackInEntity.Id;
                //        stackLogEntity.StackLocation = stackInEntity.StackLocation;
                //        stackLogEntity.LogType = "1";
                //        stackLogEntity.Note = "全部出库；货品：" + stackInEntity.ProductName + "从" + stackInEntity.StackLocation + "全部出库。出库类型为：" + stackInEntity.Type;
                //        stackLogEntity.CreateTime = DateTime.Now;
                //        stackLogEntity.UpdateTime = DateTime.Now;
                //        stackLogBLL.Insert(stackLogEntity);
                //    }
                //}
                //else
                //{
                //    stackInEntity.ProductCount = stackInEntity.ProductCount - newCount;
                //    var flag = stackInBLL.Update(stackInEntity);
                //    if (flag)
                //    {
                //        StackLogEntity stackLogEntity = new StackLogEntity();
                //        stackLogEntity.Id = Guid.NewGuid().ToString();
                //        stackLogEntity.StackOrderId = stackInEntity.Id;
                //        stackLogEntity.StackLocation = stackInEntity.StackLocation;
                //        stackLogEntity.LogType = "1";
                //        stackLogEntity.Note = "部分出库；货品：" + stackInEntity.ProductName + "从" + stackInEntity.StackLocation + "部分出库。出库类型为：" + stackInEntity.Type + " ；数量为：" + newCount;
                //        stackLogEntity.CreateTime = DateTime.Now;
                //        stackLogEntity.UpdateTime = DateTime.Now;
                //        stackLogBLL.Insert(stackLogEntity);
                //    }
                //}
                #endregion 
            }
            catch (Exception ex)
            {
                MessageBox.Show("出库失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                _log.Error(ex.Message);
                this.Close();
            }
        }


        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void StackOutSettingForm_Load(object sender, EventArgs e)
        {
            if (stackInEntity != null)
            {
                var list1 = stackLocationBLL.GetList().OrderByDescending(x => x.UpdateTime).ToList().Select(x => x.StackName).ToArray();
                this.cmbStackLocation.Items.AddRange(list1);
                List<string> typeList = new List<string>();
                typeList.Add("常规销售");
                typeList.Add("特价销售");
                this.cmbType.Items.AddRange(typeList.ToArray());
                this.cmbType.SelectedIndex = 0;

                this.cmbProductName.Text = stackInEntity.ProductName;
                this.txtProductCode.Text = stackInEntity.ProductCode;
                this.cmbStackLocation.Text = stackInEntity.StackLocation;
                this.numUniPrice.Value = Convert.ToDecimal(stackInEntity.UniPrice);
                this.numProductCount.Maximum = stackInEntity.ProductCount;
            }
        }
    }
}
